package com.chmingx.JavaBasic.thread.readWrite;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 演示读写锁
 *
 * 多个线程同时读，但只要一个线程在写，其他线程就必须等待
 */
public class ReadWriteCache {
    private Map<String, Object> map = new HashMap<>();

    // 创建读写锁
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private final Lock rlock = readWriteLock.readLock();
    private final Lock wlock = readWriteLock.writeLock();

    // 写数据
    public void put(String key, Object value) {
        // 写锁加锁
        wlock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "正在写操作" + key);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写完毕");
        } finally {
            // 释放写锁
            wlock.unlock();
        }
    }

    // 取数据
    public Object get(String key) {
        rlock.lock();
        Object result;
        try {
            System.out.println(Thread.currentThread().getName() + "正在读数据" + key);
            result = map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取完毕");
        }finally {
            rlock.unlock();
        }
        return result;
    }
}
